package com.lc202309;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * Description:
 *
 * @Create 2023/9/7 22:03
 * @Version 1.0
 */
public class Solution20 {
    public boolean isValid1(String s) {
        int length = s.length();
        if (length % 2 != 0) {
            return false;
        }
        String str;
        char peek;
        char item;
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < length; i++) {
            item = s.charAt(i);
            if (stack.size() == 0) {
                stack.push(item);
                continue;
            }
            peek = stack.peek();
            str = "" + peek + item;
            if (str.equals("()") || str.equals("[]") || str.equals("{}")) {
                stack.pop();
                continue;
            }
            stack.push(item);
        }
        return stack.empty();
    }


    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        int length = s.length();
        if (length % 2 != 0) {
            return false;
        }
        char peek;
        char item;
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < length; i++) {
            item = s.charAt(i);
            if (stack.size() == 0) {
                stack.push(item);
                continue;
            }
            peek = stack.peek();
            if (map.getOrDefault(peek,'?') == item) {
                stack.pop();
                continue;
            }
            stack.push(item);
        }
        return stack.empty();
    }
}
